import {_decorator, CCInteger, Component, EventTouch, Input, input, Node, find} from 'cc';
import {EventManager} from "db://assets/Scripts/Common/EventManager";
import {EventType} from "db://assets/Scripts/Common/EventType";
import {NodePath} from "db://assets/Scripts/Common/NodePath";

const {ccclass, property} = _decorator;

/**
 * UI管理类
 */
@ccclass('UIMain')
export class UIMain extends Component {
    /**
     * 玩家节点
     */
    private playerNode: Node = null;
    /**
     * 移动速度
     */
    public speed: number = 1;
    /**
     * 正在触摸
     */
    public static TOUCHING: boolean = false;

    start() {

    }

    onEnable() {
        // 注册触摸事件
        input.on(Input.EventType.TOUCH_START, this.touchStart, this);
        input.on(Input.EventType.TOUCH_MOVE, this.touchMove, this);
        input.on(Input.EventType.TOUCH_END, this.touchEnd, this);
        input.on(Input.EventType.TOUCH_CANCEL, this.touchEnd, this);

        // 注册创建玩家事件
        EventManager.on(EventType.RESTART, this.onRestart, this);
    }

    onDisable() {
        // 注销触摸事件
        input.off(Input.EventType.TOUCH_MOVE, this.touchMove, this);
        input.off(Input.EventType.TOUCH_START, this.touchStart, this);
        input.off(Input.EventType.TOUCH_END, this.touchEnd, this);
        input.off(Input.EventType.TOUCH_CANCEL, this.touchEnd, this);

        // 取消注册创建玩家事件
        EventManager.off(EventType.RESTART, this.onRestart, this);
    }

    update(deltaTime: number) {

    }

    touchStart(event: EventTouch) {
        // 记录触摸状态
        UIMain.TOUCHING = true;
        EventManager.emit(EventType.ATTACKING, true);
    }

    touchMove(event: EventTouch) {
        // 当玩家死亡时
        if (!this.playerNode || !this.playerNode.active) {
            // 直接返回
            return;
        }

        // 触摸距离
        let delta = event.touch.getDelta();
        // 玩家位置
        let playerPosition = this.playerNode.position;
        // 设置玩家位置
        let x = playerPosition.x + 0.01 * delta.x * this.speed;
        if (x > 4) {
            x = 4;
        }
        if (x < -4) {
            x = -4;
        }
        let z = playerPosition.z - 0.01 * delta.y * this.speed;
        if (z > 7) {
            z = 7;
        }
        if (z < -7) {
            z = -7;
        }
        this.playerNode.setPosition(x, playerPosition.y, z);
    }

    touchEnd(event: EventTouch) {
        // 记录触摸状态
        UIMain.TOUCHING = false;
        EventManager.emit(EventType.ATTACKING, false);
    }

    /**
     * 当创建玩家时
     */
    private onRestart() {
        this.playerNode = find(NodePath.PLAYER);
    }
}